package com.adcc.loadsheet.billing.service.impl;

import com.adcc.loadsheet.billing.entity.contractuser.ContractUserEntity;
import com.adcc.loadsheet.billing.entity.permission.PermissionEntity;
import com.adcc.loadsheet.billing.mapper.mysql.PbStaffEntityMapper;
import com.adcc.loadsheet.billing.mapper.mysql.contractuser.ContractUserEntityMapper;
import com.adcc.loadsheet.billing.mapper.mysql.permission.ContractUserPermissionEntityMapper;
import com.adcc.loadsheet.billing.mapper.mysql.permission.PermissionEntityMapper;
import com.adcc.loadsheet.billing.service.PermissionService;
import com.adcc.loadsheet.billing.util.BillingTools;
import com.adcc.loadsheet.billing.util.LogUtil;
import com.adcc.loadsheet.billing.util.SystemOperationLogType;
import com.adcc.loadsheet.billing.vo.TreeVO;
import com.adcc.loadsheet.billing.vo.contractuser.ContractUserEntityVO;
import com.adcc.loadsheet.billing.vo.permission.PermissionEntityVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 权限service实现类
 */
@Service
public class PermissionServiceImpl extends BasisServiceImpl implements PermissionService {

    @Autowired
    PbStaffEntityMapper pbStaffEntityMapper;

    @Autowired
    ContractUserEntityMapper contractUserEntityMapper;

    @Autowired
    ContractUserPermissionEntityMapper contractUserPermissionEntityMapper;

    @Autowired
    PermissionEntityMapper permissionEntityMapper;

    //查询合同用户（分页）
    @Override
    public PageInfo<ContractUserEntityVO> selectContractUserForPage(Map<String, Object> map){
        Integer pageNum = Integer.valueOf(map.get("pageNum").toString());
        Integer pageSize = Integer.valueOf(map.get("pageSize").toString());
        PageHelper.startPage(pageNum, pageSize);
        //合同用户
        Page<ContractUserEntity> entityPage = (Page<ContractUserEntity>) contractUserEntityMapper.select(map);

        Page<ContractUserEntityVO> voPage = new Page<>(pageNum, pageSize);
        voPage.setPages(entityPage.getPages());
        voPage.setTotal(entityPage.getTotal());
        entityPage.stream().forEach(entity -> voPage.add(entity.toVO()));
        return new PageInfo<>(voPage);
    }

    //查询权限
    @Override
    public List<PermissionEntityVO> selectPermissions(Map<String, Object> map){
        List<PermissionEntityVO> res = Lists.newArrayList();
        List<PermissionEntity> permissionEntityList = permissionEntityMapper.select(map);
        permissionEntityList.forEach(entity -> res.add(entity.toVO()));
        return res;
    }

    //获取关联权限Tree，并设置是否选中
    @Override
    public List<TreeVO> getPermissionsTreeNode(Integer contractUserId){
        List<TreeVO> vos = Lists.newArrayList();

        //与合同用户绑定的权限（区分合同用户和非合同用户）
        List<Integer> permissionIds = contractUserPermissionEntityMapper.selectPermissionIds(contractUserId);
        //全部权限
        List<PermissionEntity> permissionEntityList = permissionEntityMapper.select(null);
        if (permissionEntityList != null && permissionEntityList.size() > 0) {
            TreeVO vo;
            Boolean isParent;
            for (PermissionEntity entity : permissionEntityList) {
                isParent = entity.getParentPermissionId() == 0 ? true : false;
                vo = new TreeVO(entity,true,isParent);
                if (permissionIds != null && permissionIds.contains(entity.getFunctionPermissionId())) {
                    vo.setChecked(true);
                }
                vos.add(vo);
            }
        }
        return vos;
    }

    //编辑关联用户
    @Override
    @Transactional(transactionManager = "mysqlTransactionManager")
    public String editPermissions(Integer contractUserId,String functionPermissionIds){
        String res = "";
        try {
            //记录删除操作日志
            ContractUserEntity contractUserEntity = contractUserEntityMapper.selectByPrimaryKey(contractUserId);
            List<String> permissionDescriptions1 = permissionEntityMapper.selectPermissionDescriptionsByContractUserId(contractUserId);//已关联的
            List<String> permissionDescriptions2 = permissionEntityMapper.selectPermissionDescriptionsByIds(functionPermissionIds); //重新关联的
            //获取差别
            Map<String,String> map = BillingTools.getDifference(permissionDescriptions1, permissionDescriptions2);
            String less = map.get("less").toString();
            String more = map.get("more").toString();
            String logContent = "";
            if(!Strings.isNullOrEmpty(less)){
                logContent = "修改合同用户“" + contractUserEntity.getUserAbbrev() + "”权限：删除权限（" + less.replace(",", "、") + "）";
            }
            if(!Strings.isNullOrEmpty(more)){
                logContent += Strings.isNullOrEmpty(logContent) ? "修改合同用户“" + contractUserEntity.getUserAbbrev() + "”权限：增加权限（" + more.replace(",","、") + "）" : "，增加权限（" + more.replace(",","、") + "）";
            }
            if(!Strings.isNullOrEmpty(logContent)){
                LogUtil.operationLog(SystemOperationLogType.Permission_Operation.ordinal(), logContent, userContext.getCurrentUser().getUsername());
            }

            //保存权限，删除后再存
            contractUserPermissionEntityMapper.deleteByContractUserId(contractUserId);
            if(!Strings.isNullOrEmpty(functionPermissionIds)){
                contractUserPermissionEntityMapper.insertByBatch(contractUserId,functionPermissionIds);
            }
            res = "修改关联用户成功";
        }catch (Exception ex) {
            throw ex;
        }
        return res;
    }
}